import React, { Component } from 'react';

// 导入封装的方法（注册，登录）
import { getNew_login,getUser_login } from '../api/index'

import '../styles/Login/Login.css'
class LoginJsx extends Component {
    constructor(props) {
        super(props);
        this.state = {
             phone: '',
             pass: '',
             agree: false
        }
    }

    handleChange(e) {
        this.setState({
            [e.target.name]: e.target.type === 'checkbox' ? e.target.checked : e.target.value
        })
    }
    // 点击注册
    newLogin() {
        getNew_login({'phone':this.state.phone,'pass':this.state.pass}).then((res)=>{
            console.log(res);
        })
    }
    // 点击登录
    login() {
        console.log(this.state);
        var rphone = /^1[34578][0-9]{9}$/;
        if(!rphone.test(this.state.phone)) {
            alert('手机号码不符合')
        } else if(!this.state.agree) {
            alert('请先勾选同意后再进行登录')
        } else {
            getUser_login({'phone':this.state.phone,'pass':this.state.pass}).then((res)=>{
                if(res.data.code === 400) {
                    alert('用户名或密码错误！！！')
                } else if(res.data.code === 200) {
                    alert('登录成功！！！');
                    console.log(res);
                    localStorage.setItem('token',res.data.token);
                    localStorage.setItem('userId',res.data.userinfo.id);
                    localStorage.setItem('name',res.data.userinfo.phone);
                    localStorage.setItem('pic',res.data.userinfo.avatarUrl);
                    this.props.history.push('/index')
                }
            })
        }
    }

    render() {
        return (
            <div className='myLogin'>
                <p className='title'>密码登录</p>
                <input name='phone' type="text" value={ this.state.phone} onChange={(e)=>{ this.handleChange(e)}} placeholder='请输入手机号码'/>
                <input name='pass' type="text" value={ this.state.pass} onChange={(e)=>{ this.handleChange(e)}} placeholder='请输入密码'/>
                <button onClick={ ()=>{this.login()} }>登录</button>
                <button onClick={ ()=>{this.newLogin()} }>注册</button>
                <div className='minBox'>
                    <input name='agree' type="checkbox" className='sele' checked={ this.state.agree} onChange={(e)=>{ this.handleChange(e)}}/>
                    <p>我已阅读并同意用户协议和隐私政策</p>
                </div>
            </div>
        );
    }
}

export default LoginJsx;